package com.cm.sys.framework.application;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/***
 * 自定义异常返回类
 * 
 * @author yxq18
 *
 */
public class ResponseResult {

    /***
     * 状态码
     */
    private int code;
    /***
     * 返回信息
     */
    private String message;
    /***
     * 返回对象
     */
    private JSONObject data;

    public ResponseResult() {
        this(new JSONObject());
    }

    public ResponseResult(ApiResponseCode statusCodeEnum) {
        this.code = statusCodeEnum.getCode();
        this.message = statusCodeEnum.getMessage();
        this.data = null;
    }

    public ResponseResult(ApiResponseCode statusCodeEnum, JSONObject data) {
        this.code = statusCodeEnum.getCode();
        this.message = statusCodeEnum.getMessage();
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public JSONObject getData() {
        return data;
    }

    public ResponseResult(JSONObject data) {
        this.code = ApiResponseCode.SUCCESS.getCode();
        this.data = data;
        this.message = ApiResponseCode.SUCCESS.getMessage();
    }

    public void setSuccess(boolean success) {
        if (success) {
            this.code = ApiResponseCode.SUCCESS.getCode();
            this.message = ApiResponseCode.SUCCESS.getMessage();
        } else {
            this.code = ApiResponseCode.ERROR.getCode();
            this.message = ApiResponseCode.ERROR.getMessage();
        }
    }

    public void setData(JSONObject data) {
        this.data = data;
    }

    public <T> void set(String key, T object) {
        if (this.data == null) {
            this.data = new JSONObject();
        }
        this.data.put(key, object);
    }

    public void setMap(Map<String, Object> map) {
        this.data = new JSONObject(map);
    }

    public void setObject(Object obj) {
        this.data = (JSONObject)JSON.toJSON(obj);

    }

    public JSONObject toResultJson() {
        JSONObject json = new JSONObject();
        json.put("code", this.code);
        json.put("message", this.message);
        json.put("data", (this.data == null ? new JSONObject() : this.data));
        return json;
    }

}
